<template>
  <div class="preview_form_container">
    <el-form  ref="formModel" :model="formModel" label-position="top">
      <div class="widget_form_list">
        <div v-for="(el, i) in data.match" :key="el.key" :style="{width: el.fieldConfig.width || '33.3%'}">
          <previewSelectedItem
            v-if="el.customType == 'selectedGroup'"
            :defaultValue="formModel[el.fieldName]"
            v-model="formModel[el.fieldName]"
            :selectedElement="data.selectedConfigList[getSelectedIndex(el.placeholder)]"
            :element="el"
            :disabled="disabled"></previewSelectedItem>
          <preview-form-item
            v-else
            :element="el"
            :disabled="disabled"
            :vm = "formModel"
            :index="i"
            :data="data">
          </preview-form-item>
        </div>
      </div>
      <el-row class="marinRow" v-if="data && data.tables" style="padding: 0 10px">
        <div v-for="(table, i) in data.tables">
          <table width="100%" border="1" cellspacing="0" cellpadding="0">
            <thead>
              <tr>
                <th v-for="field in table.fields">{{field}}</th>
                <th><el-button size="mini" type="primary" icon="el-icon-plus" round @click="addTableRow(table.tableName)"></el-button></th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item,row) in  tableModel[table.tableName]">
                <td v-for="fieldName in table.fields">
                  <el-input v-model="item[fieldName]" :size="size" :disabled="disabled" @input="onTableInput()"></el-input>
                </td>
                <td><el-button size="mini" type="warning" icon="el-icon-delete" round @click="deleteRow(table.tableName,row)"></el-button></td>
              </tr>
            </tbody>
          </table>
        </div>
      </el-row>
      <el-row class="marinRow" v-if="isShowFix">
        <el-col :span="8" class="colBox">
          <el-form-item :label="$t('合同正文')" prop="contractFile" :rules="rf_rules({required:true})">
            <!--<rfUpload :param="uploadParam" :autoUpload="true"></rfUpload>-->
            <el-upload class="upload" ref="upload" :action="uploadUrl" :with-credentials="true"
                       :data="uploadParam"
                       :disabled="disabled"
                       :multiple="false"
                       accept=".doc,.docx"
                       :file-list = "fixData.contractFile.name?[fixData.contractFile]:[]"
                       :on-success="handleContractSuccess"
                       :on-change="handleUploadFile"
                       :on-remove="handleRemove"
            >
              <el-button v-if="!disabled" style="margin-left: 10px;" size="small" type="primary" icon="el-icon-upload2">{{$t('选择文件')}}</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="colBox">
          <el-form-item :label="$t('相关附件')" prop="contractAttachments">
            <!--<rfUpload :param="uploadParam" :autoUpload="true"></rfUpload>-->
            <el-upload class="upload" ref="uploadAttach" :action="uploadUrl" :with-credentials="true"
                       :data="attachParam"
                       :disabled="disabled"
                       multiple
                       :file-list = "fixData.contractAttachments"
                       :on-success="handleAttachSuccess"
                       :on-remove="handleRemoveAttach"
            >
              <el-button v-if="!disabled" style="margin-left: 10px;" size="small" type="primary" icon="el-icon-upload2">{{$t('选择文件')}}</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!--<el-button @click="test">test</el-button>-->
  </div>
</template>

<script>
  import {mapGetters} from "vuex"
  import previewFormItem from './previewFormItem'
  import previewSelectedItem from './previewSelectedItem'
  import rfUpload from '@/components/Upload/RfUploadFile/index'
  import api from '@/utils/api.js'
  export default {
    name: 'previewForm',
    components: {
      previewFormItem,
      previewSelectedItem,
      rfUpload
    },
    props: {
      data: {
        type: Object,
        default: () => ({
          match: [],
          selectedConfigList: [],
          tables: []
        })
      },
      isShowFix: { // 是否显示固定字段
        type: [Boolean, Number],
        default: false
      },
      content: {
        type: Object,
        default: () => ({})
      },
      disabled: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        formModel: {},
        tableModel: {},
        fixData: {contractFile: {}, contractAttachments: []}, // 动态表单外，固定的字段
        uploadedContractAttachments: [],
        uploadUrl: api.uploadFileUrl(),
        uploadParam: {category: 'contract'},
        attachParam: {category: 'attachment'}
      }
    },
    computed: {
      ...mapGetters(['size']),
    },
    watch: {
      content: {
        handler (val) {
          this.formModel = val.content || {}
          this.fixData = val
          if (this.formModel) {
            if (this.formModel.multipleData) {
              let mul = JSON.parse(this.formModel.multipleData)
              Object.assign(this.formModel, mul)
            }
            if (!this.fixData.contractFile) this.fixData.contractFile = {}
            this.formModel.contractFile = this.fixData.contractFile
            if (!this.fixData.contractAttachments) this.fixData.contractAttachments = []
            if (!this.formModel.tables) {
              this.formModel.tables = []
            }
          }
        },
        immediate: true
      },
      data: {
        handler (val) {
          if (this.data && this.data.tables) {
            this.createTableModelByStruct(this.data.tables, this.formModel.tables)
          }
        },
        immediate: true
      },
    },
    methods: {
      getSelectedIndex (placeholder) {
        let groupName = placeholder.split('_')[1]
        let index = this.data.selectedConfigList.findIndex(item => item.group === groupName)
        return index
      },
      test () {
        this.$refs['formModel'].validate((valid) => {
          if (valid) {
            // 处理是否自定义字段，自定义字段抽取出来放在multipleData中
            let multipleData = {}
            for (let i in this.data.match) {
              if (this.data.match[i].custom) {
                let fieldName = this.data.match[i].fieldName
                multipleData[fieldName] = this.formModel[fieldName]
                delete this.formModel[this.data.match[i].fieldName]
              }
            }
            this.formModel.multipleData = JSON.stringify(multipleData)
          } else {
          }
        })
      },
      // 删除el-upload之前的文件
      handleUploadFile (file, fileList) {
        if (fileList.length > 1) {
          fileList.splice(0, 1)
        }
        this.fixData.contractFile.name = file.name
        this.formModel.contractFile = this.fixData.contractFile
      },
      handleRemove (file, fileList) {
        this.fixData.contractFile = {}
        this.formModel.contractFile = this.fixData.contractFile
      },
      handleRemoveAttach (file, fileList) {
        this.fixData.contractAttachments = fileList
      },
      handleContractSuccess (res) {
        if (res.code !== 200) {
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        } else {
          this.fixData.contractFile.url = res.data
        }
      },
      handleAttachSuccess (res, file, fileList) {
        if (res.code !== 200) {
          this.$message({
            message: res.msg,
            type: 'warning'
          })
        } else {
          this.fixData.contractAttachments = fileList
        }
      },
      checkRule () { // 检查规则是否成立
        let rules = this.data.rules ? this.data.rules : []
        let ret = true
        for (let i in rules) {
          let rule = rules[i]
          let ruleStr = rule
          if (rule) {
            for (let i in this.data.match) {
              let match = this.data.match[i]
              let fieldName = match.tableFieldName || match.fieldName
              rule = rule.replace('{{' + (match.placeholder || match.fieldName) + '}}', this.formModel[fieldName])
              ruleStr = ruleStr.replace('{{' + (match.placeholder || match.fieldName) + '}}', fieldName)
            }
            let reslut = null
            try {
              reslut = eval(rule)
            } catch (e) {}
            if (!reslut) {
              this.$alert('预设规则:' + ruleStr + '<br>结果:' + rule + '<br>请重新填入值', '预设规则不通过', {
                dangerouslyUseHTMLString: true
              })
              return reslut
            }
            ret = reslut && ret
          }
        }
        return ret
      },
      // ------------------ 动态表格相关函数----------------------------
      createTableModelByStruct (struct, tableData) { // 根据表格的结构，创建表格的model，方便被表格v-model
        if (tableData) { // 把现有的tableData数据存放在tableModel中
          tableData.forEach((table) => {
            this.tableModel[table.tableName] = table.data
          })
        }
        struct.forEach((table) => { // 如果没有初始tableData数据，就需要根据struct结构构造tableModel
          if (!this.tableModel[table.tableName]) {
            this.tableModel[table.tableName] = []
            let rowObject = {}
            table.fields.forEach((field, i) => {
              rowObject[field] = ''
            })
            this.tableModel[table.tableName].push(rowObject)
          }
        })
        console.log(this.tableModel)
      },
      onTableInput () {
        this.$forceUpdate()
      },
      addTableRow (tableName) { // 添加动态行
        this.data.tables.forEach((table) => {
          if (table.tableName === tableName) {
            let rowObject = {}
            table.fields.forEach((field, i) => {
              rowObject[field] = ''
            })
            this.tableModel[table.tableName].push(rowObject)
          }
        })
        this.$forceUpdate()
      },
      deleteRow (tableName, row) { // 添加行
        this.tableModel[tableName].splice(row, 1)
        this.$forceUpdate()
      },
      // ------------------ 动态表格相关函数----------------------------end
      async getModelData () {
        let ret = null
        await this.$refs['formModel'].validate((valid) => {
          if (valid) {
            // 处理是否自定义字段，自定义字段抽取出来放在multipleData中
            let multipleData = {}
            for (let i in this.data.match) {
              if (this.data.match[i].custom) {
                let fieldName = this.data.match[i].fieldName
                multipleData[fieldName] = this.formModel[fieldName]
                delete this.formModel[this.data.match[i].fieldName]
              }
            }
            // 处理动态table的数据
            if (this.data.tables) {
              multipleData.tables = []
              for (let name in this.tableModel) {
                let tableData = {
                  tableName: name,
                  data: this.tableModel[name]
                }
                multipleData.tables.push(tableData)
              }
            }
            this.formModel.multipleData = JSON.stringify(multipleData)
            ret = this.formModel
          } else {
            ret = null
          }
        })
        return ret
      },
      getFixData () {
        this.fixData.contractAttachments = this.fixData.contractAttachments.map(item => {
          let {name, url, response} = item
          url = url || (response ? response.data : '')
          return {name, url}
        })
        return this.fixData
      }
    }
  }
</script>

<style lang="scss">
  .preview_form_container {
    width: 100%;
    height: 100%;
    .widget_form_list {
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;

      .el-input-number {
        &>span{
          display: none;
        }
        .el-input__inner {
          text-align: left;
          padding-left: 15px;
          padding-right: 15px;
        }
      }
    }
    .line-width-3 {
      width: calc(33.3% - 3px);
    }
    .line-width-1 {
      width: 100%;
    }

    .form-edit-widget-label {
      display: none;
    }
    .colBox {
      padding: 0 10px;
    }
  }
</style>
